<template>
  <component
    is="a-modal"
    v-model:visible="visible"
    :width="800"
    :title="title"
    :mask-closable="false"
    :ok-loading="loading"
    @cancel="close"
    @before-ok="submit">
    <!-- 表单信息 start -->
    <a-form ref="formRef" :model="formData" :rules="rules" :auto-label-width="true">
      <a-row :gutter="10">
        <a-col :span="24">
          <a-form-item label="直播名称" field="name">
            <a-input v-model="formData.name" placeholder="请输入直播名称" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="直播封面" field="cover">
            <sa-upload-image v-model="formData.cover" :limit="1" :multiple="false" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="开播时间(设置后无法修改)" field="start_time">
            <a-date-picker :disabled="mode === 'edit' ? true : false" v-model="formData.start_time" show-time value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开播时间" @ok="onOk" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="直播模式(设置后无法修改)" field="webinar_type">
            <sa-radio :disabled="mode === 'edit' ? true : false" v-model="formData.webinar_type" :options="data_moshi" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="直播样式(设置后无法修改)" field="show_type">
            <sa-radio :disabled="mode === 'edit' ? true : false" v-model="formData.show_type" :options="data_status" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item :disabled="mode === 'edit' ? true : false" label="是否生成回放(设置后无法修改)" field="auto_record">
            <sa-radio v-model="formData.auto_record" :options="data_record" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否延时显示" field="list_show">
            <sa-radio v-model="formData.list_show" :options="data_list_show" />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="formData.list_show===1">
          <a-form-item label="延时显示时间" field="delay_time">
            <a-date-picker show-time placeholder="请选择延时显示时间" @ok="yanchionOk" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="视频选择" field="record_id">
            <a-select  :disabled="mode === 'edit' ? true : false" v-model="formData.record_id" :options="liveList" @change="handleChange" placeholder="请选择视频" style="width: 300px;" />
          </a-form-item>
        </a-col>
        <!-- 清晰度选择-->
            <a-form-item v-if="VQualityList.length > 0" label="清晰度选择" prop="quality">
                <a-radio-group v-model="formData.bitrate" @change="getQualityInfo">
                    <a-radio
                        v-for="item in VQualityList"
                        :disabled="mode === 'edit' ? true : false"
                        :key="item.quality"
                        :value="item.bitrate"
                        >{{ item.name }}</a-radio
                    >
                </a-radio-group>
            </a-form-item>
        <div
              v-if="formData.quality && formData.record_id && VQualityList.length > 0"
              style="letter-spacing: 1px"
              class="bg-[#f3f3f3] w-[80%] h-[100px] ml-[80px] pl-2 text-[12px] flex flex-col justify-center mb-2"
          >
              <div v-if="formData.quality !== 'same'">
                  <div class="mb-2">分辨率：{{ qualityInfo?.quality }}</div>
                  <div class="mb-2">最高码率: {{ qualityInfo?.bitrate }}kbps</div>
                  <div class="text-[12px] text-[#999]">
                      *实际转码效果可能存在部分偏差，请以转码完成效果为准
                  </div>
              </div>
              <div v-if="formData.quality === 'same'" class="text-[12px] text-[#999]">
                  *观看码率与原视频一致，请注意码率过高时的流量消耗
              </div>
          </div>
        <a-col :span="24">
          <a-form-item label="直播间可见" field="is_look">
            <sa-radio v-model="formData.is_look" :options="data_is_look" />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="formData.is_look!==1">
          <a-form-item :label-col="{span: 24}" :wrapper-col="{span: 24}" :label="formData.is_look===2?'指定团长或者代理下可见':'指定团长或者代理下不可见'" field="viewable">
            <a-input v-model="formData.viewable" :placeholder="formData.is_look===2?'请输入可见团长或者代理ID，用英文,隔开':'请输入不可见团长或者代理ID，用英文,隔开'" />
            <div style="width: 250px;text-align: right;color: #999;">代理ID请用英文逗号隔开</div>
          </a-form-item>
          
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否显示倒计时" field="count_down">
            <sa-radio v-model="formData.count_down" :options="data_count_down" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否显示在线人数" field="hide_watch">
            <sa-radio v-model="formData.hide_watch" :options="data_online_count" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否显示热度" field="hide_pv">
            <sa-radio v-model="formData.hide_pv" :options="data_online_count" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <!-- 表单信息 end -->
  </component>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
// import api from '../../api/goods/goods'
import api from '@/api/live/live'
import tool from '@/utils/tool'

const emit = defineEmits(['success'])
// 引用定义
const visible = ref(false)
const loading = ref(false)
const formRef = ref()
const mode = ref('')
let title = computed(() => {
  return '定时直播' + (mode.value == 'add' ? '-新增' : '-编辑')
})

const data_moshi = ref([
  {
    label: '视频直播',
    value: 2,
  },
  {
    label: '互动直播(可连麦)',
    value: 3,
  },
])
const data_status = ref([
  {
    label: '竖屏直播',
    value: 0,
  },
  {
    label: '横屏直播',
    value: 1,
  },
])

const data_online_count = ref([
  {
    label: '不显示',
    value: 0,
  },
  {
    label: '显示',
    value: 1,
  },
])

const data_is_look = ref([
  {
    label: '全部可见',
    value: 1,
  },
  {
    label: '部分代理可见',
    value: 2,
  },
  {
    label: '部分代理不可见',
    value: 3,
  },
])

const data_record = ref([
  {
    label: '不生成',
    value: 0,
  },
  {
    label: '生成',
    value: 1,
  },
])

const data_list_show = ref([
  {
    label: '不延迟',
    value: 0,
  },
  {
    label: '延迟',
    value: 1,
  },
])

const data_count_down = ref([
  {
    label: '不显示',
    value: 2,
  },
  {
    label: '显示',
    value: 1,
  },
])
const liveList = ref([])
// 表单信息
const formData = reactive({
  room_id: null,
  name: '',
  cover: '',
  webinar_type:2,
  show_type: 0,
  auto_record: 0,
  start_time: '',
  is_look: 1,
  list_show: 0,
  list_show_time: '',
  count_down: 2,
  hide_watch: 0,
  hide_pv: 0,
  record_id: null,
  quality: '',
  bitrate_profile: '',
  bitrate: '',
  viewable: '',
})

// 验证规则
const rules = {
  name: [{ required: true, message: '直播间名称必需填写' }],
  cover: [{ required: true, message: '直播间封面必需填写' }],
  start_time: [{ required: false, message: '直播时间必需填写' }],
  record_id: [{ required: true, message: '请选择直播视频' }],
}

const onOk = (value) => {
  console.log(value)
  formData.start_time = value
}
const yanchionOk = (value) => {
  formData.list_show_time = value
}

// 打开弹框
const open = async (type = 'add',item) => {
  mode.value = type
  visible.value = true
  getLiveList()
  formRef.value.resetFields()
  await initPage(item)
}

// 初始化页面数据
const initPage = async (item) => {
  
  if (mode.value === 'edit') {
    const resp = await api.RoomDetail({ room_id: item.room_id })
    formData.name = resp.data.info.name
    formData.cover = resp.data.info.cover
    formData.webinar_type = resp.data.info.webinar_type
    formData.show_type = resp.data.info.show_type
    formData.auto_record = resp.data.info.auto_record
    formData.start_time = tool.timestampToTime(resp.data.info.start_time)
    formData.is_look = resp.data.info.is_look
    formData.list_show = resp.data.info.list_show
    if(formData.list_show == 1){
      formData.list_show_time = tool.timestampToTime(resp.data.info.list_show_time)
    }
    formData.count_down = resp.data.info.count_down
    formData.hide_watch = resp.data.info.hide_watch
    formData.hide_pv = resp.data.info.hide_pv
    formData.room_id = resp.data.info.room_id
    formData.bitrate = Number(resp.data.info.bitrate)
    formData.quality = resp.data.info.quality
    formData.bitrate_profile = resp.data.info.bitrate_profile
    formData.record_id = resp.data.info.record_id
    formData.viewable = resp.data.info.viewable
    if(mode.value === 'edit'){
      handleChange(formData.record_id)
    }
  }
}

const getLiveList = async ()=>{
  liveList.value = []
  let result = await api.listVideo({
    page: 1,
    limit: 10000,
  })
  result.data.data.forEach(item => {
    liveList.value.push({label:item.name,value:item.record_id})
  })
  
}

const VQualityList = ref([])
const qualityInfo = ref({})
const handleChange = async (value) => {
  const res = await api.videoDefinition({
    record_id: value,
  })
  VQualityList.value = res.data.list
  if(mode.value === 'add'){
    formData.bitrate = VQualityList.value[0].bitrate
    formData.quality = VQualityList.value[0].quality
    formData.bitrate_profile = VQualityList.value[0].bitrate_profile
    qualityInfo.value = VQualityList.value[0]
  }else{
    qualityInfo.value = VQualityList.value.find((item) => item.bitrate == formData.bitrate)
  }
 
}
const getQualityInfo = (e) => {
    formData.quality = VQualityList.value.find((item) => item.bitrate == formData.bitrate)?.quality
    formData.bitrate_profile = VQualityList.value.find((item) => item.bitrate == formData.bitrate)?.bitrate_profile
    qualityInfo.value = VQualityList.value.find((item) => item.bitrate == formData.bitrate)
}


// 数据保存
const submit = async (done) => {
  const validate = await formRef.value?.validate()
  if (!validate) {
    loading.value = true
    let data = { ...formData }
    let result = {}
    if (mode.value === 'add') {
      // 添加数据
      data.id = undefined
      console.log(data)
      result = await api.createTimedLive(data)
    } else {
      // 修改数据
      result = await api.updateRoom(data)
    }
    if (result.code === 200) {
      Message.success('操作成功')
      emit('success')
      done(true)
    }
    // 防止连续点击提交
    setTimeout(() => {
      loading.value = false
    }, 500)
  }
  done(false)
}

// 关闭弹窗
const close = () => {
  visible.value = false
  formRef.value.resetFields()
  VQualityList.value = []
  qualityInfo.value = {}
}

defineExpose({ open})
</script>
